package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserLoginMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserLoginService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
@Slf4j
@Service
public class UserLoginServiceImp implements UserLoginService {
    private static final String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties properties;
    @Autowired
    private UserLoginMapper userLoginMapper;
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //请求微信提供的网址，来返回openid，看其是否合法appid	string	 	是
        // 小程序 appId
        //secret	string	 	是	小程序 appSecret
        //js_code	string	 	是	登录时获取的 code
        //grant_type	string	 	是	授权类型，此处只需填写 authorization_code
        HashMap<String,String> hm=new HashMap<>();
        hm.put("appId", properties.getAppid());
        hm.put("secret", properties.getSecret());
        hm.put("grant_type", "authorization_code");
        hm.put("js_code", userLoginDTO.getCode());
        String s = HttpClientUtil.doGet(LOGIN_URL, hm);
        log.info(s);
        String s1 = s.split("}")[0] + "}";
        //将得到的json格式数据转化,需要其中的openid键值
        JSONObject jsonObject = JSONObject.parseObject(s1);
        String openId = jsonObject.getString("openid");
        //看openid是否为空
        if(openId==null){
            throw new LoginFailedException("登录失败！");
        }
        //查看数据库，看这个用户是否已经注册
        User select = userLoginMapper.select(openId);
        if(select==null){
            //为空，自动注册
            select = User.builder().openid(openId).createTime(LocalDateTime.now()).build();
            userLoginMapper.insert(select);
        }

        return select;
    }
}
